﻿using iHouse.Common.Membership;
using iHouse.Model.Cache;
using iHouse.Model.Repository;
using iHouse.Model.Repository.Interface;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Dependencies;
using System.Linq;

namespace iHouse.Web.Infrastructure
{
    public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;

        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;

            var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where typeof(ApiController).IsAssignableFrom(t)
                                  select t;

            foreach (Type t in controllerTypes)
            {
                container.RegisterType(typeof(ApiController), t, t.FullName);
            }
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }

        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new UnityResolver(child);
        }

        public void Dispose()
        {
            container.Dispose();
        }
    }
}